import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import { useEffect } from 'react';
const { RangePicker } = DatePicker;
const FORMAT = {
  date: 'YYYY-MM-DD',
  year: 'YYYY',
  dateTime: 'YYYY-MM-DD HH:mm:ss',
  dateTimeMinute: 'YYYY-MM-DD HH:mm',
};
const RangePickerCom = ({
  format,
  formatType = 'date',
  showTime,
  placeholder = ['开始时间', '结束时间'],
  onChange,
  defaultValue,
  setValue,
}) => {
  const type = FORMAT[formatType];
  useEffect(() => {
    if (defaultValue) {
      onChange?.([defaultValue[0], defaultValue[1]]);
    }
  }, [defaultValue]);
  const handleChange = (data, dateString) => {
    if (data) {
      onChange?.([dateString[0], dateString[1]]);
      setValue?.(dateString[0], dateString[1]);
    } else {
      onChange && onChange(null);
      setValue?.(null, null);
    }
  };
  return (
    <RangePicker
      className="w"
      defaultValue={
        defaultValue
          ? [dayjs(defaultValue[0], type), dayjs(defaultValue[1], type)]
          : null
      }
      showTime={{ format: 'HH:mm' }}
      format={type}
      placeholder={placeholder}
      onChange={handleChange}
    />
  );
};

export { RangePickerCom };
